#coding=utf-8

import cgi
import os
import trackurl
import datetime
import time

from google.appengine.ext.webapp import template


from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson

global NUMBER
NUMBER = 1000

#start = [2010,4,29]
#end = time.localtime()[0:3]
class Fetchurl(webapp.RequestHandler):
  def post(self):
    trackurl.update_database()
    self.redirect('/')

class MainPage(webapp.RequestHandler):
  def get(self):

    global NUMBER

    record_query = trackurl.Datalog.all().order('-date')
    records = record_query.fetch(NUMBER)

    qfts  = "%r"%([[time.mktime(i.date.timetuple())*1000, str(i.qfts )] for i in records ])
    xfts  = "%r"%([[time.mktime(i.date.timetuple())*1000, str(i.xfts )] for i in records ])
    clfts = "%r"%([[time.mktime(i.date.timetuple())*1000, str(i.clfts)] for i in records ])
    qfmj  = "%r"%([[time.mktime(i.date.timetuple())*1000, str(i.qfmj )] for i in records ])
    xfmj  = "%r"%([[time.mktime(i.date.timetuple())*1000, str(i.xfmj )] for i in records ])
    clfmj = "%r"%([[time.mktime(i.date.timetuple())*1000, str(i.clfmj)] for i in records ])

    template_values = {
      'qfmj': qfmj,
      'xfmj': xfmj,
      'clfmj': clfmj,
      'qfts': qfts,
      'xfts': xfts,
      'clfts': clfts,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class RPCHandler(webapp.RequestHandler):
    """ Allows the functions defined in the RPCMethods class to be RPCed."""
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods()

    def get(self):
        func = None

        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
                return
            else:
                func = getattr(self.methods, action, None)

        if not func:
            self.error(404) # file not found
            return

        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (simplejson.loads(val),)
            else:
                break
        result = func(*args)
        self.response.out.write(simplejson.dumps(result))


class RPCMethods:
    """ Defines the methods that can be RPCed.
    NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """

    def Add(self, *args):
        # The JSON encoding may have encoded integers as strings.
        # Be sure to convert args to any mandatory type(s).
        ints = [int(arg) for arg in args]
        return sum(ints)



application = webapp.WSGIApplication(
                                     [
                                     ('/', MainPage),
                                     ('/rpc', RPCHandler),
                                     ('/fetch', Fetchurl),
                                      ],
                                      #('/doit', Doit),
                                      #('/delit', Delit)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

